package com.example.stujava.module.xiangxue.reflect;

import com.example.stujava.module.xiangxue.reflect.entity.Student;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class ReflectUnit {
    public static void main(String[] args) throws InvocationTargetException, IllegalAccessException {
        String str = "LuMa";
        Class<String> cla = (Class<String>) str.getClass();
        boolean assignableFrom = cla.isAssignableFrom(String.class);
        boolean instance = cla.isInstance(new Integer(5));
        System.out.println("assignableFro=" + assignableFrom + "instance=" + instance);

        Student stu = new Student();
        Class stuClass = stu.getClass();
        Field[] declaredFields = stuClass.getDeclaredFields();//可以获取所有属性
        for (Field field : declaredFields) {
            System.out.println(field.getName());
        }
        Field[] fields = stuClass.getFields();
        for (Field field : fields) {
            System.out.println(field.getName());//除了private修饰属性
        }
        System.out.println("打印方法⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐");
        Method[] declaredMethods = stuClass.getDeclaredMethods();
        Method[] methods = stuClass.getMethods();
        for (Method method : declaredMethods) {
            System.out.println(method.getName());//Class类所有方法不包括父类
            if (method.getName().equals("setGrade")) {
                method.invoke(stu, "199");
            }
        }
        System.out.println("打印方法2⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐");
        for (Method method : methods) {
            System.out.println(method.getName());//Class类和父类的方法，不包括private
            if (method.getName().equals("getGrade")) {
                System.out.println(method.invoke(stu));//199
            }
        }
        System.out.println("访问私有方法⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐");
        //setAccessible(true)
        try {
            //获取指定私有方法
            Method setIdMethod = stuClass.getDeclaredMethod("setId", int.class);
            setIdMethod.setAccessible(true);//设置取消访问检查
            setIdMethod.invoke(stu, 19);
            Method getIdMethod = stuClass.getDeclaredMethod("getId");
            Object invoke = getIdMethod.invoke(stu);
            System.out.println("invoke=" + invoke);
            setIdMethod.setAccessible(false);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
    }
}
